package it.niedermann.android.markdown.markwon.textwatcher

import android.text.Editable
import android.text.TextUtils
import android.text.TextWatcher
import androidx.annotation.ColorInt
import androidx.core.content.ContextCompat
import com.gitee.wsl.common.ui.ext.isDarkThemeActive
import io.noties.markwon.base.R
import it.niedermann.android.markdown.MarkdownUtil
import it.niedermann.android.markdown.markwon.MarkwonMarkdownEditor
import it.niedermann.android.markdown.model.SearchSpan

class SearchHighlightTextWatcher(
    originalWatcher: TextWatcher,
    private val editText: MarkwonMarkdownEditor
) : InterceptorTextWatcher(originalWatcher) {
    private var searchText: CharSequence? = null
    private var current: Int? = null

    @ColorInt
    private var color: Int

    @ColorInt
    private val highlightColor: Int
    private val darkTheme: Boolean

    init {
        val context = editText.context
        color = ContextCompat.getColor(context, R.color.search_color)
        highlightColor = ContextCompat.getColor(context, R.color.bg_highlighted)
        darkTheme = context.isDarkThemeActive
    }

    fun setSearchText(searchText: CharSequence?, current: Int?) {
        this.current = current
        if (TextUtils.isEmpty(searchText)) {
            this.searchText = null
            val text = editText.text
            if (text != null) {
                MarkdownUtil.removeSpans(text, SearchSpan::class.java)
            }
        } else {
            this.searchText = searchText
            afterTextChanged(editText.text!!)
        }
    }

    fun setSearchColor(@ColorInt color: Int) {
        this.color = color
        afterTextChanged(editText.text!!)
    }

    override fun afterTextChanged(s: Editable) {
        originalWatcher.afterTextChanged(s)
        if (searchText != null) {
            MarkdownUtil.removeSpans(s, SearchSpan::class.java)
            MarkdownUtil.searchAndColor(s, searchText, current, color, highlightColor, darkTheme)
        }
    }
}